<template>
    <div class="app-container">

        <!-- <div class="app-container-left">
            <tree ref="tree" @set-tree-data="setTreeData" @go_menu="go_menu" />
        </div> -->

        <div :class="['filter-container',{'open':formState}]">
            <a v-if="screenState" class="form-more" href="#" title="更多筛选" @click="formState = !formState"><i
                    :class="formState ? 'el-icon-caret-top':'el-icon-caret-bottom'" /></a>
            <!-- <el-form ref="form" :model="form" @keyup.enter.native="handleFilter()" label-width="80px"> -->

            <!-- 筛选框需要些双份 一种是没有展开状态下的  只有主要的几个筛选框，另一种是全部的筛选框都展示 也就是展开状态下的 -->
            <!-- 没有展开状态下的筛选框 -->
            <el-form v-if="!formState" ref="filtrateForm" :inline="true" :model="filtrateForm" label-width="80px">
                <el-form-item label="园区名称:">
                    <el-select v-model="filtrateForm.parkId" placeholder="请选择" @change="park_change" style="width:240px;">
                        <el-option v-for="item in park_options" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="选择房屋:">
                    <el-cascader :options="houses_options" :props="houses_props" style="width:240px;" @change="houses_change"
                        ref="house_tree" collapse-tags clearable>
                    </el-cascader>
                </el-form-item>

                <el-form-item label="房屋名称">
                    <el-input v-model.trim="filtrateForm.houseName" placeholder="请输入" style="width:240px;" clearable />
                </el-form-item>

                <!-- <el-form-item label="客户姓名">
                    <el-input v-model.trim="filtrateForm.customerName" placeholder="请输入" style="width:240px;" clearable />
                </el-form-item> -->

                <el-form-item v-if="!formState">
                    <el-button class="filter-item" @click="handleFilter">
                        查询
                    </el-button>
                    <!-- <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                            @click="handleCreateHouse">新增房屋</el-button>
                        <el-button :loading="downloadLoading1" style="margin-left: 10px;" class="filter-item" type="primary"
                            @click="handleDownloadMock">
                            下载模板
                        </el-button>
                        <el-upload class="upload-demo" style="margin-left: 10px;" :headers="headers" :show-file-list="false"
                            :action="action" :on-success="handleSuccess" multiple :limit="1" name="file">
                            <el-button type="primary">导入</el-button>
                        </el-upload>
                        <el-button :loading="downloadLoading" style="margin-left: 10px;" class="filter-item" type="primary"
                            @click="handleDownload">
                            导出
                        </el-button> -->
                </el-form-item>
            </el-form>

            <!-- 展开状态下的筛选框 -->
            <el-form v-if="formState" ref="form" :inline="true" :model="filtrateForm" label-width="80px">

                <el-form-item label="园区名称:">
                    <el-select v-model="filtrateForm.parkId" placeholder="请选择" @change="park_change" style="width:240px;">
                        <el-option v-for="item in park_options" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="选择房屋:">
                    <el-cascader :options="houses_options" :props="houses_props" style="width:240px;" @change="houses_change"
                        ref="house_tree" collapse-tags clearable>
                    </el-cascader>
                </el-form-item>

                <el-form-item label="收款单号">
                    <el-input v-model.trim="filtrateForm.payCode" placeholder="请输入" style="width:240px;" clearable />
                </el-form-item>

                <el-form-item label="房屋名称">
                    <el-input v-model.trim="filtrateForm.houseName" placeholder="请输入" style="width:240px;" clearable />
                </el-form-item>
                <el-form-item label="客户姓名">
                    <el-input v-model.trim="filtrateForm.customerName" placeholder="请输入" style="width:240px;" clearable />
                </el-form-item>
                <el-form-item label="收费项目:">
                    <el-select v-model="filtrateForm.itemsId" placeholder="请选择" style="width:240px;">
                        <el-option v-for="item in project_options" :key="item.id" :label="item.itemsName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="账单日期">
                    <el-date-picker v-model="filtrateForm.beginTime_endTime_bill" style="width:100%" type="monthrange"
                        format="yyyy 年 MM 月 DD日" value-format="yyyy-MM-DD" range-separator="至" start-placeholder="开始月份"
                        end-placeholder="结束月份">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="收款日期">
                    <el-date-picker v-model="filtrateForm.beginTime_endTime_pay" style="width:100%" type="monthrange"
                        format="yyyy 年 MM 月 DD日" value-format="yyyy-MM-DD" range-separator="至" start-placeholder="开始月份"
                        end-placeholder="结束月份">
                    </el-date-picker>
                </el-form-item>

            </el-form>
            <div v-if="formState" class="filter-button">
                <el-button class="filter-item" @click="handleFilter">
                    查询
                </el-button>
                <!-- <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                    @click="hongChong()">批量红冲账单</el-button> -->
                <!-- <el-button :loading="downloadLoading1" style="margin-left: 10px;" class="filter-item" type="primary"
                        @click="handleDownloadMock">
                        下载模板
                    </el-button>
                    <el-upload class="upload-demo" style="margin-left: 10px;" :headers="headers" :show-file-list="false" :action="action"
                        :on-success="handleSuccess" multiple :limit="1" name="file">
                        <el-button type="primary">导入</el-button>
                    </el-upload>
                    <el-button :loading="downloadLoading" style="margin-left: 10px;" class="filter-item" type="primary"
                        @click="handleDownload">
                        导出
                    </el-button> -->
            </div>

        </div>

        <div :class="['table',{'open':formState}]">
            <div class="table-container">
                <el-table :key="tableKey" v-loading="listLoading" row-key="menuId" height="100%" :data="list" border fit
                    highlight-current-row style="width: 100%;" @selection-change="selectionChangeHandle">

                    <el-table-column type="selection" header-align="center" align="center" width="50" />

                    <el-table-column prop="parkName" header-align="center" align="center" label="园区名称" />

                    <el-table-column prop="name" header-align="center" align="center" label="房屋名称" width="180">
                        <template
                            slot-scope="scope">{{scope.row.buildingName}}-{{scope.row.unitName}}-{{scope.row.floorName}}-{{scope.row.houseName}}</template>
                    </el-table-column>

                    <el-table-column prop="customerName" header-align="center" align="center" label="客户名称" />

                    <el-table-column prop="itemsName" header-align="center" align="center" label="收费项目" />

                    <el-table-column prop="billBeginTime" header-align="center" align="center" width="180" label="收费开始日期">
                        <template slot-scope="scope">{{ scope.row.billBeginTime | toData() }}</template>
                    </el-table-column>

                    <el-table-column prop="billEndTime" header-align="center" align="center" width="180" label="收费结束日期">
                        <template slot-scope="scope">{{ scope.row.billEndTime | toData() }}</template>
                    </el-table-column>

                    <!-- <el-table-column prop="billRealMoney" header-align="center" align="center" label="应收(元)" />

                    <el-table-column prop="billFreeMoney" header-align="center" align="center" label="减免(元)" />

                    <el-table-column prop="billRealPayMoney" header-align="center" align="center" label="实收(元)" /> -->

                    <el-table-column prop="billAllMoney" header-align="center" align="center" label="应收金额(元)">
                        <el-table-column :label="'合计：'+billAllMoney_" header-align="center" align="center">
                            <template slot-scope="scope">{{ scope.row.billAllMoney  }}</template>
                        </el-table-column>
                    </el-table-column>

                    <el-table-column prop="billFreeMoney" header-align="center" align="center" label="减免金额(元)">
                        <el-table-column :label="'合计：'+billFreeMoney_" header-align="center" align="center">
                            <template slot-scope="scope">{{ scope.row.billFreeMoney }}</template>
                        </el-table-column>
                    </el-table-column>

                    <el-table-column prop="billRealMoney" header-align="center" align="center" label="实际应收金额(元)">
                        <el-table-column :label="'合计：'+billRealMoney_" header-align="center" width="140" align="center">
                            <template slot-scope="scope">{{ scope.row.billRealMoney }}</template>
                        </el-table-column>
                    </el-table-column>

                    <!-- <el-table-column prop="settlements" header-align="center" align="center" label="收款方式" />
                    <el-table-column prop="billPrepaidMoney" header-align="center" align="center" label="预存冲抵(元)" /> -->
                    <!-- <el-table-column prop="type" header-align="center" align="center" label="房屋功能" />
                        <el-table-column prop="area" header-align="center" align="center" label="面积(m²)" />
                        <el-table-column prop="state" header-align="center" align="center" label="房屋状态">
                            <template slot-scope="scope">{{ scope.row.state | houseStateFilter  }}</template>
                        </el-table-column>
                        <el-table-column prop="updateTime" header-align="center" align="center" width="180" label="最后编辑时间">
                            <template slot-scope="scope">{{ scope.row.updateTime  }}</template>
                        </el-table-column>
                        <el-table-column prop="updateUserName" header-align="center" align="center" label="编辑人" /> -->
                    <!-- <el-table-column header-align="center" align="center" width="150" label="操作">
                        <template slot-scope="scope">
                            <el-button v-permission="['sys:config:update']" type="text" size="small" @click="handleUpdateHouse(scope.row)">
                                收款备注
                            </el-button>
                            <el-button v-permission="['sys:config:update']" type="text" size="small" @click="hongChong(scope.row)">
                                红冲实收
                            </el-button>
                            <el-button v-permission="['sys:config:delete']" type="text" size="small" @click="deleteHandle(scope.row)">删除
                                </el-button>
                        </template>
                    </el-table-column> -->

                </el-table>
            </div>
        </div>

        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <!-- tree新增修改 -->
        <!-- <add-or-update-tree v-if="addOrUpdateVisibletree" ref="addOrUpdatetree" @getList="handleFilter" @getTree="getTree" /> -->
        <!-- 新增修改 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @getList="handleFilter" />
        <!-- 侧面弹框 -->
        <!-- <side-dialog v-if="SideDialogVisible" ref="SideDialog"></side-dialog> -->

    </div>
</template>

<script>


import { getFinancebilldetail, getChargeList, getHongchong, getPaiedbill } from '@/api/charge'// 请求数据  收费标准
import { getParkListAll, getTreeHouseList } from '@/api/assets';
// import { HouseExportExcel, downloadMock, HouseImportExcel } from '@/api/index'// 请求数据
import permission from '@/directive/permission/index.js' // 权限判断指令
import { houseState, houseType, houseFunction } from '@/utils/enum' //字典
import { toDate } from '@/utils'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination 分页组件

import AddOrUpdate from './add-or-update' // 新增或者修改弹框




export default {
    name: 'LayoutTable',
    components: { Pagination, AddOrUpdate },
    directives: { permission }, // 指令
    // 过滤 {{row.status | statusFilte}}
    // html代码中，{{}}中实现filters顺序是 {{参数 | filters函数 | filters函数 | ...}}
    // 后面可以多个filters函数，前面filters函数return的结果是后面filters函数的参数。
    // 并且可以在过滤函数后面加上（）里面加上其他的参数。如 filterTwo('同学')
    filters: {
        toData (data) {
            return toDate(data)
        },
        typeFilter (type) {
            return calendarTypeKeyValue[type]
        },
        houseStateFilter (status) {
            let map = houseState;
            return map[status]
        }
    },
    data () {
        return {
            screenState: true, // 筛选框是否展示下拉按钮
            formState: false, // 筛选框的 开合
            // 筛选框的 form 表单
            filtrateForm: {
                parkId: '',//园区id
                houseIds: [],//选中的 房屋
                payCode: '',//收款单号
                houseName: '',//房屋名称
                customerName: '',//客户名称
                itemsId: '',//项目id
                beginTime_endTime_pay: ['', ''],//收款日期
                beginTime_endTime_bill: ['', ''],//账单日期
            },
            rules: { // 表单验证
            },
            dataListSelections: [], // 批量删除选中
            // 树形选择结果
            treeData: {
                id: '', //房屋id
                name: '',
                depth: '',
                code: ''
            },
            tableKey: 0,
            list: [], // 表格数据
            total: 0, // 总条数
            listLoading: true, // 表格加载数据时的 loading
            listQuery: { // 表格当前页 和 当前页的展示数量
                page: 1,
                limit: 20
            },
            addOrUpdateVisible: false,
            park_options: [],//园区list
            project_options: [],//项目list
            houses_options: [],// 单元/层/房屋 tree
            houses_props: {
                // children: 'children',
                // label: 'label',
                label: 'storeyName',
                value: 'id',
                children: "list",
                multiple: true
            }


        }
    },
    computed: {
        // houseFunction_ () {
        //     let arr = [{ lable: '全部', value: '' }]
        //     for (let key in houseFunction) {
        //         arr.push({
        //             lable: houseFunction[key],
        //             value: key
        //         })
        //     }
        //     return arr
        // }
        //三个合计金额
        billAllMoney_ () {
            if (this.list.length < 1) return "0";
            let numberS = this.list.map(item => {
                return item.billAllMoney ? item.billAllMoney * 1 : 0
            })
            let number = eval(numberS.join("+")).toString()
            return number
        },
        billFreeMoney_ () {
            if (this.list.length < 1) return "0";
            let numberS = this.list.map(item => {
                return item.billFreeMoney ? item.billFreeMoney * 1 : 0
            })
            let number = eval(numberS.join("+")).toString()
            return number
        },
        billRealMoney_ () {
            if (this.list.length < 1) return "0";
            let numberS = this.list.map(item => {
                return item.billRealMoney ? item.billRealMoney * 1 : 0
            })
            let number = eval(numberS.join("+")).toString()
            return number
        }
    },
    created () {
        this.getPark()
        this.getList()
    },
    methods: {
        // 树选择
        setTreeData (data) {
            if (!data.name) return;
            console.log('树形选择结果', data)
            this.treeData.id = data.id
            this.treeData.parkId = data.parkId
            this.treeData.type = data.type
            // this.treeData.name = data.name
            // this.treeData.depth = data.depth
            // this.treeData.code = data.code
            this.handleFilter()
        },
        //获取园区list
        async getPark () {
            const res = await getParkListAll().catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            this.park_options = [{ name: '全部', id: '' }].concat(data)
            // console.log(data)

        },
        //获取 房屋树形
        async getTreeHouseList () {
            let params = {
                parkId: this.filtrateForm.parkId
            }
            const res = await getTreeHouseList(params).catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            let data_ = data.filter(el => {
                return el.parkId == this.filtrateForm.parkId
            });
            this.houses_options = this.set_tree(data_[0].list)
            console.log("房屋", data_)
        },
        set_tree (data) {
            function treeArr (arr) {
                arr.forEach((item, index) => {
                    if (item.name) item.storeyName = item.name;
                    if (item.list && item.list.length > 0) {
                        treeArr(item.list)
                    }
                })
                return arr
            }
            let res = treeArr(data)
            return res
        },
        //获取项目list
        async getCharge () {
            let params = {
                parkId: this.treeData.parkId
            }
            const res = await getChargeList(params).catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            this.project_options = [{ itemsName: "全部", id: '' }].concat(data)
            console.log("项目list", data)
            // this.project_change(this.temp.project_id)
        },
        // 获取表格数据
        async getList () {
            this.listLoading = true
            // 筛选+分页
            const params = Object.assign({
                parkId: this.filtrateForm.parkId,
                houseIds: this.filtrateForm.houseIds + '',
                payCode: this.filtrateForm.payCode,
                houseName: this.filtrateForm.houseName,
                customerName: this.filtrateForm.customerName,
                itemsId: this.filtrateForm.itemsId,
                payStartTime: this.filtrateForm.beginTime_endTime_pay ? this.filtrateForm.beginTime_endTime_pay[0] : '',
                payEndTime: this.filtrateForm.beginTime_endTime_pay ? this.filtrateForm.beginTime_endTime_pay[1] : '',
                billStartTime: this.filtrateForm.beginTime_endTime_bill ? this.filtrateForm.beginTime_endTime_bill[0] : '',
                billEndTime: this.filtrateForm.beginTime_endTime_bill ? this.filtrateForm.beginTime_endTime_bill[1] : '',
                state: 2//
            }, this.listQuery)
            // 请求
            const res = await getPaiedbill(params).catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            console.log(data)

            this.list = data.list
            this.total = data.totalCount
            this.listLoading = false
        },
        // 重新获取表格数据 页码归为1
        handleFilter () {
            this.listQuery.page = 1
            this.getList()
        },
        //刷新tree
        getTree () {
            this.$refs.tree.getTree()
        },
        go_menu (e) {

        },
        // 新增数据-打开弹框
        handleCreateHouse (param) {
            this.addOrUpdateVisible = true
            // let param = param
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('create', param)
            })
        },
        // 修改 -- 打开弹框
        handleUpdateHouse (row) {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('update', row)
            })
        },
        // 批量删除数据 - 多选
        selectionChangeHandle (val) {
            this.dataListSelections = val
        },
        // 删除
        deleteHandle (data) {
            console.log(this.dataListSelections, data)
            const idS = data ? [data.id] : this.dataListSelections.map(item => { return item.id })
            const nameS = data ? [data.paiedCode] : this.dataListSelections.map(item => { return item.paiedCode })
            let params = {
                // ids: '[' + idS.join(",") + ']'
                ids: idS + ""
            }
            this.$confirm(`确定对[${nameS.join('、')}]进行[红冲]操作?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 提交删除
                console.log(idS)
                const { code, message } = await getHongchong(params)
                // 成功
                this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        this.handleFilter()// 刷新数据
                    }
                })
            })
        },

        //>>>>>
        //选择园区
        park_change (e) {
            console.log(e)
            this.getTreeHouseList()
            this.getCharge()
        },
        //选择房屋
        houses_change (data, checked, indeterminate) {
            // let houses = this.$refs.house_tree.getCheckedNodes(false, false);
            let houses_ = data.map(el => {
                return el[el.length - 1]
            })
            this.filtrateForm.houseIds = houses_
        }

    }
}
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import '~@/styles/layout-table.scss';
$rowLength: 2;
@media all and (min-width: 1659px) {
    $rowLength: 3;
    @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
    $rowLength: 3;
    @include calculation($rowLength: $rowLength);
}
</style>
